package com.jsy.learnnetty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/10/13
 */

@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("new client channel active");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("client channel loss");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = ((ByteBuf) msg);
        String message = in.toString(StandardCharsets.UTF_8);
        System.out.println("from client ---- " + message);

        if (message.contains("end")) {
            System.out.println("try to close client channel");
            try {
                ctx.close().addListener(ChannelFutureListener.CLOSE).sync();
                System.out.println("close client channel successfully...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            ctx.writeAndFlush(in);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
